package ch.ti.bfh.app.loodel.web.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public abstract class AbstractPrimefacesAutoCompleteConverter<T> implements Converter {

    private static final Logger logger = LoggerFactory.getLogger(AbstractPrimefacesAutoCompleteConverter.class);

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (StringUtils.isNotBlank(value)) {
            T returnObject = getAsObjectFromAutocompleteSuggestionValue(value);
            if (returnObject != null) {
                return returnObject;
            } else {
                logger.debug("No Autocomplete suggestion item has been determined, Using now Object value '{}'", value);
                return value;
            }
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        String returnString = getAsStringForAutocompleteSuggestionValue(value);
        if (returnString != null) {
            return returnString;
        }
        if (value != null) {
            logger.debug("No Autocomplete suggestion item has been determined. Using now String value '{}'", value.toString());
            return value.toString();
        }
        logger.debug("Neither an Autocomplete suggestion has been determined nor has value has been set");
        return "";
    }

    protected abstract T getAsObjectFromAutocompleteSuggestionValue(String value);

    public abstract String getAsStringForAutocompleteSuggestionValue(Object value);
}
